import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: 扫描目录文件，进行文件内容的查找
 * 找到名称或者内容中包含指定字符的所有普通文件
 * 找到了就把对应的文件路径打印出来
 */
public class Demo14 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //输入源路径
        System.out.print("请输入目标目录：");
        String src = scanner.nextLine();
        File srcFile = new File(src);
        if(!srcFile.isDirectory()) {
            System.out.println("输入的文件目录有误");
            return;
        }
        //输入要查找的内容
        System.out.print("请输入查找内容：");
        String dest = scanner.nextLine();
        scanDir(srcFile, dest);
    }

    private static void scanDir(File srcFile, String dest) {
        File[] files = srcFile.listFiles();
        if(files == null) {
            return;
        }
        for (File f:files) {
            if(f.isDirectory()) {
                scanDir(f, dest);
                continue;
            }
            if(containsDest(f, dest)) {
                try {
                    System.out.println(f.getCanonicalPath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private static boolean containsDest(File f, String dest) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)) {
            String name = f.getName();
            if(name.contains(dest)) {
                return true;
            }
            char[] buffer = new char[1024];
            while(true) {
                int len = reader.read(buffer);
                if(len == -1) {
                    //读取结束，未找到目标字符串
                    break;
                }
                stringBuilder.append(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.indexOf(dest) != -1;
    }
}
